package isquirrel.servlets;

import isquirrel.UserManager;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

import org.json.JSONException;

/**
 * Servlet implementation class Router
 */
public class Router extends HttpDBServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Router() {
        super();
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException {
		String auth_method = request.getParameter("au");
		HttpSession session = request.getSession(true);
		
		if (auth_method != null){
			if (auth_method.equals("to")){
				/* the request originates from the bookmarklet */
				String token = (String) request.getParameter("t");
				String uname = (String) request.getParameter("user");
				if (UserManager.tokenLogin(uname,token)){
					session.setAttribute("user", uname);
					response.sendRedirect("servlet/Profiler?nextp=home");
				}
				else {
					response.sendRedirect("error");
				}
			}
		}
		else {	
			/* the user has navigated to the website */ 
			if (session.getAttribute("user") != null){
				/* session is alive */
				response.sendRedirect("servlet/Profiler?nextp=home");
			}
			else{
				/* sorry, need to login again */
	        	response.sendRedirect("login");
			}
		}
		
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
	}

}
